package org.community.test.repositary.util;

import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
@Data
@Slf4j
public class MinioUtil {

    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;


    //上传文件
    public void upload(MultipartFile customFile,String fileName) {


            InputStream in = null;
            try {
                in = customFile.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(this.getBucketName())
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .contentType(customFile.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


    }





    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public byte[] download(String prefix,String fileName) {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] bytes = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(prefix+fileName).build());

            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            bytes = out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }




    //生成流式响应体
    public ResponseEntity<byte[]> bytesToResponseEntity(byte[] bytes, String fileName){
        ResponseEntity<byte[]> responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //封装返回值
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
//            responseEntity = new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
            responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    //生成流式响应体
    public ResponseEntity<byte[]> bytesToResponseEntityVideo(byte[] bytes, String fileName){
        ResponseEntity<byte[]> responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
        headers.setContentDispositionFormData(fileName, fileName);
        responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        return responseEntity;
    }



    /**
     * 批量删除文件对象
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }


    /**
     * 查看文件对象
     * @param prefix 图片所在文件夹
     * @return 存储bucket内文件对象信息
     */
    public List<String> listObjects(String prefix) {
        Iterable<Result<Item>> results = new ArrayList<>();

        minioClient.listObjects(
                ListObjectsArgs.builder().bucket(this.getBucketName()).prefix(prefix).build()
        );

        List<String> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                objectItems.add(item.objectName());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    public void uploadByBatch(Map<String,MultipartFile> files){
        for (Map.Entry<String,MultipartFile> entry:files.entrySet()) {
            upload(entry.getValue(), entry.getKey());
        }
    }


}
